import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_module/common/extensions/cached_network_image_extension.dart';
import 'package:flutter_module/common/widget/video/video_controller.dart';
import 'package:flutter_module/style/colors.dart';
import 'package:orientation/orientation.dart';
import 'package:video_player/video_player.dart';

/// Create by kyluzoi
/// Date: 2021-08-23
///
/// Description: 播放器组件

class VideoView extends StatefulWidget {
  final String url; // 播放路径
  final String? cover; // 封面图
  final bool autoPlay; // 是否自动播放
  final bool looping; // 是否循环播放
  final double? aspectRatio;
  final Widget? overlayUI;

  const VideoView(
      {Key? key,
      required this.url,
      this.cover,
      this.autoPlay = false,
      this.looping = false,
      this.aspectRatio,
      this.overlayUI})
      : super(key: key);

  @override
  _VideoViewState createState() => _VideoViewState();
}

class _VideoViewState extends State<VideoView> {
  VideoPlayerController? _videoPlayerController; //video_player播放器Controller
  ChewieController? _chewieController; //chewie播放器Controller

  //封面
  get _placeholder => FractionallySizedBox(
        heightFactor: 1,
        child: Center(
          child: YFNetworkImage(
            resource: widget.cover,
            fit: BoxFit.cover,
          ),
        ),
      );

  //进度条颜色配置
  get _progressColors => ChewieProgressColors(
      playedColor: ThemeColors.blue009CFE,
      handleColor: ThemeColors.blue009CFE,
      backgroundColor: Colors.grey,
      bufferedColor: ThemeColors.redEF5D5E);

  @override
  void initState() {
    //初始化播放器设置
    _videoPlayerController = VideoPlayerController.network(widget.url);
    initChewieController();

    super.initState();
  }

  @override
  void dispose() {
    _chewieController?.removeListener(_fullScreenListener);
    _videoPlayerController?.dispose();
    _chewieController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_chewieController == null) print("videoView not init");
    double screenWidth = MediaQuery.of(context).size.width;
    double playerHeight = widget.aspectRatio == null
        ? screenWidth
        : screenWidth / widget.aspectRatio!;
    return WillPopScope(
      onWillPop: () async {
        if (_chewieController != null && _chewieController!.isFullScreen) {
          _chewieController!.toggleFullScreen();
          return false;
        } else {
          return true;
        }
      },
      child: Container(
        width: screenWidth,
        height: playerHeight,
        color: Colors.black38,
        child: _chewieController != null
            ? Chewie(
                controller: _chewieController!,
              )
            : Container(),
      ),
    );
  }

  void _fullScreenListener() {
    Size size = MediaQuery.of(context).size;
    if (size.width > size.height) {
      OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
    }
  }

  ///黑色线性渐变
  blackLinearGradient({bool fromTop = false}) {
    return LinearGradient(
        begin: fromTop ? Alignment.topCenter : Alignment.bottomCenter,
        end: fromTop ? Alignment.bottomCenter : Alignment.topCenter,
        colors: [
          Colors.black54,
          Colors.black45,
          Colors.black38,
          Colors.black26,
          Colors.black12,
          Colors.transparent
        ]);
  }

  void initChewieController() async {
    await _videoPlayerController!.initialize();
    _chewieController = ChewieController(
        videoPlayerController: _videoPlayerController!,
        // aspectRatio: widget.aspectRatio,
        autoPlay: widget.autoPlay,
        looping: widget.looping,
        placeholder: _placeholder,
        allowMuting: false,
        allowPlaybackSpeedChanging: false,
        customControls: MaterialVideoControls(
          showLoadingOnInitialize: false,
          showBigPlayIcon: false,
          bottomGradient: blackLinearGradient(),
          overlayUI: widget.overlayUI,
        ),
        materialProgressColors: _progressColors);

    //fix iOS无法正常退出全屏播放问题
    _chewieController?.addListener(_fullScreenListener);
    setState(() {

    });
  }
}
